import { DeleteOutlined, EditOutlined, PlusOutlined, SearchOutlined } from '@ant-design/icons'
import { Button, Col, Form, Input, Row, Space, Table, Drawer, message, Popconfirm } from 'antd'
import React, { useEffect, useState } from 'react'
import { diseAddAPI, diseDelAPI, diseEditAPI, diseaseAPI } from '../service/desease'
import { render } from '@testing-library/react'
import moment from 'moment';

const { TextArea } = Input;

function Disease() {
  //定义状态获取疾病数据列表
  const [diseList, setDiseList] = useState([])
  //抽屉打开或者关闭
  const [open, setOpen] = useState(false)
  //定义状态 同步抽屉标题
  const [drawerTitle, setDrawerTitle] = useState('')
  //定义状态用于更新列表
  const [a, setA] = useState(0)
  //定义状态保存当前总数据量
  const [total,setTotal] = useState(0)
  //定义状态保存修改的ID
  const [id,setId] = useState()
  //创建表单实例
  const [myForm] = Form.useForm()

  //副作用钩子模拟生命周期
  useEffect(() => {
    diseaseAPI().then((res) => {
      // console.log(res);
      setDiseList(res.data)
      //查询到数据以后保存当前总数据量，分页使用
      setTotal(res.total)
    })
  }, [a])
  

  return <>
    <Space direction='vertical' size="large" style={{ width: '100%', height: '100%', overflow: 'auto' }}>
      <Row>
        <Col span={24}>
          <Form layout='inline'
            onFinish={async (v)=>{
              //发送请求获取查询啊到的参数 ，异步
              const res = await diseaseAPI(v)
              // console.log(res);
              //把查询的参数渲染到页面上
              setDiseList(res.data)
            }}
          >
            <Form.Item name="title">
              <Input placeholder='请输入疾病名称'></Input>
            </Form.Item>
            <Form.Item>
              <Button type='primary' htmlType='submit' icon={<SearchOutlined />}>
                查询
              </Button>
            </Form.Item>
          </Form>
        </Col>
      </Row>
      <Row>
        <Col span={24}>
          <Button type='primary' icon={<PlusOutlined />}
            onClick={() => {
              setOpen(true)//打开抽屉
              setDrawerTitle('新增疾病')
              setId()
            }}
          >新增疾病</Button>
        </Col>
      </Row>
      <Row>
        <Col span={24}>
          <Table
          pagination={{
            total,
            defaultCurrent:1,
            onChange: async (pno)=>{
              console.log(pno);
              const res = await diseaseAPI({pno})
              console.log(res);
              setDiseList(res.data)
            }
          }}
            rowKey='did'//使用ID作为唯一标识
            dataSource={diseList}
            columns={
              [
                {
                  title: 'ID',
                  dataIndex: 'did',
                  key: 'did',
                  align: 'center'
                },
                {
                  title: '疾病名称',
                  dataIndex: 'title',
                  key: 'title',
                  align: 'center'
                },
                {
                  title: '变更时间',
                  dataIndex: 'mtime',
                  key: 'mtime',
                  align: 'center',
                  render: (v) => {
                    // console.log(v);
                    const date = Date.parse(new Date())
                    //时间戳为空时返回当前date
                    if (v === null) {
                      return moment(date).format('YYYY-MM-DD HH:mm:ss')
                    }
                    return <>
                      {moment(v).format('YYYY-MM-DD HH:mm:ss')}

                    </>
                  }
                },
                {
                  title: '操作',
                  dataIndex: 'op',
                  key: 'op',
                  align: 'center',
                  render: (v,r) => {
                    return (
                        <Space>
                          <Button type='primary' icon={<EditOutlined />} size="small"
                            onClick={ async ()=>{
                              console.log(r);
                              setOpen(true)//打开抽屉
                              setDrawerTitle('编辑信息')
                              //Form自带API.把当前信息添加到抽屉组件中
                              myForm.setFieldsValue(r)
                              setId(r.did)//设置当前ID
                            }}
                          />
                          <Popconfirm
                            title="删除提示"
                            description="你确认要删除当前数据吗？"
                            okText="确认"
                            cancelText="取消"
                            //点击确认的回调
                            onConfirm={async()=>{
                              // console.log(r);
                              //请求接口，点击删除当前项  异步
                              const res = await diseDelAPI({did: r.did})
                              // console.log(res);
                              if(res.code===200){
                                message.success('删除成功')
                                setA(a + 1)
                              }else{
                                message.error('删除失败')
                              }
                            }}
                          >
                            <Button type='primary' icon={<DeleteOutlined />} size="small" danger />
                          </Popconfirm>
                        </Space>
                    )
                  }
                }
              ]}
          />
        </Col>
      </Row>
    </Space>
    {/* 抽屉 */}
    <Drawer
      title={drawerTitle}
      width={600}
      maskClosable={false}
      placement="right"
      destroyOnClose
      onClose={() => {
        //点击遮罩层叉叉清空
        setOpen(false)
        setId()
      }}
      open={open}
    >
      <Form 
        labelCol={{ span: 5 }}
        preserve={false}//修改表单时退出或关闭表单清空里面的值
        form={myForm}
        onFinish={async (v) => {
          console.log(v);
          if(id){
            //发送请求 修改病情(这次需要传递参数把id传过来 是否有当前数据)
            const res = await diseEditAPI({...v,did:id})
            // console.log('修改',res);
            if(res.code===200){
              message.success('疾病修改成功')
            }
          }else{
            //post异步请求接口 添加病情
            const res = await diseAddAPI(v)
            console.log(res);
            if(res.code===200){
              message.success('疾病添加成功')
            }
          }
          
          //状态变化渲染页面
          setA(a + 1)
          //关闭抽屉
          setOpen(false)

        }}
      >
        <Form.Item label="疾病名称" name="title">
          <Input placeholder="请输入疾病名称" />
        </Form.Item>
        <Form.Item label="疾病介绍" name="profile">
          <TextArea placeholder="请输入疾病介绍" style={{ height: '120px' }} />
        </Form.Item>
        <Form.Item label="症状表现" name="symptom">
          <TextArea placeholder="请输入症状表现" style={{ height: '120px' }} />
        </Form.Item>
        <Form.Item label="诊断建议" name="diagnose">
          <TextArea placeholder="请输入诊断结果及建议" style={{ height: '120px' }} />
        </Form.Item>
        <Form.Item style={{ textAlign: "right" }}>
          <Button type='primary' htmlType='submit'>保存</Button>
        </Form.Item>
      </Form>
    </Drawer>
  </>
}

export default Disease
